<?php

/*
 * Usage:
 * 
 * Call:		hazard_view_by_latlng.php?lat=<lat>&lng=<lng>
 * Returns: 	JSON data structure for hazard information
 * 				
 */


ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');

require_once 'JSON.php';

// get lat and lng
$lat = $_GET["lat"];
$lng = $_GET["lng"];

$query = <<<QUERY
SELECT
        p.parcel_add as address,
        z.zip5 as zipcode,

        (
		SELECT 
			d1.code as code
		FROM
			damfailure as d1
		WHERE
			WITHIN
			(
				PointFromText('POINT($lng $lat)', 4326),
				d1.the_geom
			)
        ) as damfailure,

        l.potential as liquefaction,
        (g.gridcode/10.0) as pga,
        AsText(p.the_geom) as parcel
FROM
        parcels as p,
        zipcodes as z,
        liquefaction as l,
        groundmotion as g
WHERE
        WITHIN(PointFromText('POINT($lng $lat)', 4326),p.the_geom)
AND
        WITHIN(PointFromText('POINT($lng $lat)', 4326),z.the_geom)
AND
        WITHIN(PointFromText('POINT($lng $lat)', 4326),l.the_geom)
AND
        WITHIN(PointFromText('POINT($lng $lat)', 4326),g.the_geom)
LIMIT 1
QUERY;

$hazards = array();

// connect to db
$conn = pg_connect("dbname=rvha user=pgadmin password=pgadmin");
	if (!$conn)
	{
       	 	print "Unable to Connect to DB";
	        exit;
	}


$result = pg_query($query);

$location = new Location();
$location->lat = $lat;
$location->lng = $lng;

while( $arr = pg_fetch_array($result))
{
	
	$location->zipcode = $arr["zipcode"];
	$location->damfailure = $arr["damfailure"];
	$location->liquefaction = $arr["liquefaction"];
	$location->pga = $arr["pga"];
	$location->mmi = calculateMMI($location->pga); // calc shaking based on PGA
	$multipolygon = $arr["parcel"];
	$parcel = createParcelFromMultiPolygon($multipolygon);
	$parcel->address = $arr["address"];
	$location->parcel = $parcel;
}

$json = new Services_JSON();
$jsonWrapper = '{"location":';
$jsonWrapper .= $json->encode($location);
$jsonWrapper .= '}';

print $jsonWrapper;

class Location {
	
	var $lat;
	var $lng;
	var $zipcode;
	var $damfailure;
	var $liquefaction;
	var $pga;
	var $mmi;
	var $parcel;
	
	function Location()
	{

	}	
}

class Parcel {
	
	var $address;
	var $polygons = array();
	
	function Parcel()
	{

	}	
	
	function addPolygon($polygon)
	{
		array_push($this->polygons, $polygon);
	}
}

class Polygon {
	
	var $points = array();
	
	function Polygon()
	{
		
	}
	
	function addPoint($point)
	{
		array_push($this->points, $point);
	}	
	
}

class LatLng {
	
	var $lat;
	var $lng;
	
	function Polygon()
	{
		
	}	
	
}

function createParcelFromMultiPolygon($multipolygon)
{
	
	$parcel = new Parcel();
	
	// parse multipolygons
	$multipolygon = preg_replace("/MULTIPOLYGON\((.*)\)/", "$1", $multipolygon);
	$polys = preg_split("/\),\(/", $multipolygon);

	for($i=0; $i<=sizeof($polys)-1; $i++)
	{
		
		$polygon = new Polygon();
		
		// clean up the double surrounding brackets
		$poly = preg_replace("/\(\((.*)\)\)/", "$1", $polys[$i]);
		
		// parse points
		$points = split(",", $poly);
		for($j = 0; $j <= sizeof($points)-1; $j++)
		{
			
			$point = new LatLng();
			
			$p = $points[$j];
			//print $p . "<br>";
			// now split point on ' '
			$coords = split(" ", $p);
			$lng = $coords[0];
			$lat = $coords[1];
			//print "lat=$lat, lng=$lng<br>";
			
			$point->lat = $lat;
			$point->lng = $lng;
			//print_r($point);
			
			$polygon->addPoint($point);
			
		}
		
		$parcel->addPolygon($polygon);
		
	}
	
	return $parcel;
	
}

function calculateMMI($pga)
{
	/*
	 * 0.1-0.25 = MMI:VI
	 * 0.25-0.35 = MMI:VII
	 * 0.35-0.65 = MMI:VIII
	 * 0.65-+ = MMI:IX 
	 */
	$mmi = "";
	
	// VI
	if( ($pga >= 0.1) && ($pga < 0.2) )
	{
		$mmi = "VI";
	}
	
	// VI or VII
	if( ($pga == 0.2) || ($pga == 0.3) )
	{
		$mmi = "VI|VII";
	}
	
	// VIII
	if( ($pga > 0.3) || ($pga <= 0.5) )
	{
		$mmi = "VIII";
	}
		
	// VIII or IX
	if( ($pga == 0.6) || ($pga == 0.7) )
	{
		$mmi = "VIII|IX";
	}
		
	if( ($pga > 0.7) )
	{
		$mmi = "IX";
	}

	return $mmi;
}
?>